package com.ggb.reactive.security

import com.ggb.reactive.service.JwtSigner
import lombok.AllArgsConstructor
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.stereotype.Component
import reactor.core.publisher.Mono
import java.util.stream.Stream

@Component
@AllArgsConstructor
class JwtAuthenticationManager(val jwtSigner: JwtSigner): ReactiveAuthenticationManager {
    override fun authenticate(authentication: Authentication): Mono<Authentication> {
        println("访问 ReactiveAuthenticationManager  。。。。。。。。。。。")

        return Mono.just(authentication)
            .map {auth -> jwtSigner.parseToken(auth.credentials.toString()) }
            .log()
            .onErrorResume { e->
                println("验证token时发生错误，错误类型为： ${e.javaClass}，错误信息为： ${e.message}")
                Mono.empty();
            }
            .map { claims->

                UsernamePasswordAuthenticationToken(
                    claims.subject,
                    null,
                    Stream.of(claims.get(jwtSigner.authoritiesTag).toString())
                        .peek { println("权限为： $it") }
                        .map { authority -> SimpleGrantedAuthority(authority) }
                        .toList()
                )
            }

    }
}